"use client";
import {Edit, useForm} from "@refinedev/antd";
import {useParsed} from "@refinedev/core";
import {
    Form,
    Input,
    InputNumber,
    Select,
    TreeSelect,
    Descriptions,
    Tabs,
    Upload,
    Button,
    message,
    Row,
    Col
} from "antd";
import {UploadOutlined} from "@ant-design/icons";
import {useEffect, useMemo, useState} from "react";
import {selectNewsDescs} from "../../../../../common/api/news_action";
import {uploadImage} from "@common/api/upload_action";
import {getCategoryOptions} from "@common/api/category_action";
import ReactQuill from "react-quill";
import 'react-quill/dist/quill.snow.css';

export default function NewsEdit() {
    const {id} = useParsed();
    const {formProps, saveButtonProps ,formLoading} = useForm({
        resource: "project/news",
        id: id
    });
    const [availableLangs, setAvailableLangs] = useState<string[]>(['zh-CN', 'zh-TW', 'en-US']);
    const [descList, setDescList] = useState<any[]>([]);
    const [imageUrl, setImageUrl] = useState<string>('');
    const [uploading, setUploading] = useState(false);
    const [categoryTreeData, setCategoryTreeData] = useState<any[]>([]);
    const options = useMemo(() => ({
        toolbar: [
            [{header: [1, 2, false]}],
            ['bold', 'italic', 'underline', 'strike'],
            [{list: 'ordered'}, {list: 'bullet'}],
            [{color: []}, {background: []}],
            ['link'],
            ['image'],
            ['clean']
        ]
    }), []);
    useEffect(() => {
        if (formProps?.initialValues?.alias) {
            // 获取新闻描述
            selectNewsDescs(formProps.initialValues.alias).then((res: any) => {
                if (res.data && res.data.length > 0) {
                    setDescList(res.data);
                    formProps?.form?.setFieldsValue({
                        descs: res.data
                    });
                } else {
                    formProps?.form?.setFieldsValue({
                        descs: [
                            {id: undefined, lang: 'zh-CN', title: '', keyword: '', description: '', content: ''},
                            {id: undefined, lang: 'zh-TW', title: '', keyword: '', description: '', content: ''},
                            {id: undefined, lang: 'en-US', title: '', keyword: '', description: '', content: ''},
                        ]
                    });
                }
            });
        }
    }, [formProps?.initialValues?.alias]);

    // 获取分类选项
    useEffect(() => {
        getCategoryOptions().then((res: any) => {
            if (res.code === 200) {
                setCategoryTreeData(res.data || []);
            }
        }).catch((error) => {
            console.error('获取分类选项失败:', error);
        });
    }, []);

    // 监听图片字段变化
    useEffect(() => {
        if (formProps?.initialValues?.image) {
            setImageUrl(formProps.initialValues.image);
        }
    }, [formProps?.initialValues?.image]);

    return (
        <Edit saveButtonProps={saveButtonProps} isLoading={formLoading}>
            <Form {...formProps} layout="horizontal" labelCol={{span: 3}}>
                <Row>
                    <Col span={12}>
                        <Form.Item name={["category_alias"]} label="分类别名">
                            <TreeSelect
                                placeholder="请选择分类"
                                allowClear
                                treeData={categoryTreeData}
                                fieldNames={{label: 'label', value: 'value', children: 'children'}}
                                treeDefaultExpandAll
                                loading={categoryTreeData.length === 0}
                                style={{width: '100%'}}
                                showSearch
                                treeNodeFilterProp="label"
                                dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            name={["alias"]}
                            label="别名"
                            rules={[
                                {required: true, message: '请输入别名'},
                                {
                                    pattern: /^[a-zA-Z0-9_-]+$/,
                                    message: '别名只能包含字母、数字、下划线和连字符'
                                }
                            ]}
                        >
                            <Input placeholder="别名必须唯一，用于标识新闻"/>
                        </Form.Item>
                    </Col>
                </Row>
                <Form.Item name={["url"]} label="URL">
                    <Input/>
                </Form.Item>
                <Form.Item name={["image"]} label="图片">
                    <div style={{display: 'flex', gap: '8px', alignItems: 'flex-start'}}>
                        <Upload
                            name="image"
                            showUploadList={false}
                            beforeUpload={(file) => {
                                const isImage = file.type.startsWith('image/');
                                if (!isImage) {
                                    message.error('只能上传图片文件!');
                                    return false;
                                }
                                const isLt5M = file.size / 1024 / 1024 < 5;
                                if (!isLt5M) {
                                    message.error('图片大小不能超过5MB!');
                                    return false;
                                }
                                return false; // 阻止自动上传
                            }}
                            onChange={(info) => {
                                if (info.file.status === 'removed') {
                                    setImageUrl('');
                                    formProps.form?.setFieldsValue({image: ''});
                                }
                            }}
                        >
                            <Button
                                icon={<UploadOutlined/>}
                                loading={uploading}
                                onClick={async (e) => {
                                    e.preventDefault();
                                    e.stopPropagation(); // 阻止事件冒泡
                                    const input = document.createElement('input');
                                    input.type = 'file';
                                    input.accept = 'image/*';
                                    input.onchange = async (event) => {
                                        const file = (event.target as HTMLInputElement).files?.[0];
                                        if (file) {
                                            setUploading(true);
                                            try {
                                                const response: any = await uploadImage(file);
                                                console.log('Upload response:', response); // 调试日志
                                                if (response.code === 200) {
                                                    const url = response.data.url;
                                                    setImageUrl(url);
                                                    formProps.form?.setFieldsValue({image: url});
                                                    message.success('图片上传成功!');
                                                } else {
                                                    message.error(response.msg || '上传失败');
                                                }
                                            } catch (error) {
                                                console.log('Upload error:', error);
                                                message.error('上传失败');
                                            } finally {
                                                setUploading(false);
                                            }
                                        }
                                    };
                                    input.click();
                                }}
                            >
                                上传图片
                            </Button>
                        </Upload>
                        <Input
                            placeholder="或直接输入图片URL"
                            value={imageUrl}
                            onChange={(e) => {
                                setImageUrl(e.target.value);
                                formProps.form?.setFieldsValue({image: e.target.value});
                            }}
                        />
                    </div>
                    {imageUrl && (
                        <div style={{marginTop: '8px'}}>
                            <img
                                src={imageUrl}
                                alt="预览"
                                style={{
                                    maxWidth: '200px',
                                    maxHeight: '200px',
                                    objectFit: 'cover',
                                    borderRadius: '4px',
                                    border: '1px solid #d9d9d9'
                                }}
                            />
                        </div>
                    )}
                </Form.Item>
                <Row>
                    <Col span={12}>
                        <Form.Item name={["view"]} label="浏览次数">
                            <InputNumber style={{width: '100%'}}/>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item name={["sort"]} label="排序">
                            <InputNumber style={{width: '100%'}}/>
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <Form.Item name={["recommend"]} label="推荐">
                            <Select
                                options={[
                                    {label: '否', value: 0},
                                    {label: '是', value: 1}
                                ]}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item name={["status"]} label="状态">
                            <Select
                                options={[
                                    {label: '禁用', value: 0},
                                    {label: '启用', value: 1}
                                ]}
                            />
                        </Form.Item>
                    </Col>
                </Row>

                <Form.List name={["descs"]}>
                    {(fields: any[]) => {
                        // 将 fields 转为 map，方便按 lang 查找
                        const fieldMap = new Map(fields.map(f => {
                            const fieldLang = formProps.form?.getFieldValue(['descs', f.name, 'lang']);
                            return [fieldLang, f];
                        }));

                        return (
                            <Tabs defaultActiveKey="zh-CN" style={{marginTop: 24}}>
                                {availableLangs.map(lang => {
                                    const field = fieldMap.get(lang);
                                    const fieldIndex = fields.findIndex(f =>
                                        formProps.form?.getFieldValue(['descs', f.name, 'lang']) === lang
                                    );

                                    // 如果该语言没有对应字段，自动添加（比如初始化时）
                                    if (fieldIndex === -1) {
                                        // 可以在这里自动 push 一个新项，但更推荐在 useEffect 中初始化
                                        return null;
                                    }

                                    const f = fields[fieldIndex];

                                    return (
                                        <Tabs.TabPane tab={lang} key={lang}>
                                            {/* 隐藏的 lang 字段 */}
                                            <Form.Item name={[f.name, 'lang']} hidden initialValue={lang}/>

                                            <Form.Item
                                                name={[f.name, 'title']}
                                                label="标题"
                                                rules={[{required: true, message: `${lang} 标题必填`}]}
                                            >
                                                <Input/>
                                            </Form.Item>
                                            <Form.Item
                                                name={[f.name, 'keyword']}
                                                label="关键词"
                                                rules={[{required: true, message: `${lang} 关键词必填`}]}
                                            >
                                                <Input/>
                                            </Form.Item>
                                            <Form.Item
                                                name={[f.name, 'description']}
                                                label="描述"
                                                rules={[{required: true, message: `${lang} 描述必填`}]}
                                            >
                                                <Input/>
                                            </Form.Item>
                                            <Form.Item
                                                name={[f.name, 'content']}
                                                label="内容"
                                                rules={[{required: true, message: `${lang} 内容必填`}]}
                                            >
                                                <ReactQuill modules={options}/>
                                            </Form.Item>
                                        </Tabs.TabPane>
                                    );
                                })}
                            </Tabs>
                        )
                    }}
                </Form.List>
            </Form>
        </Edit>
    );
} 